﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using IdentityModels;
using Microsoft.AspNet.Identity;

namespace IdentityData
{//Repository
    public class CustomeUserStore : IUserPasswordStore<AppUser>
    {
        private readonly IdentityDataDbContext _identityDataDbContext;
        private readonly MyEntityStore<AppUser> _userStore;

        public CustomeUserStore(IdentityDataDbContext identityDataDbContext)
        {
            _identityDataDbContext = identityDataDbContext;
            _userStore = new MyEntityStore<AppUser>(identityDataDbContext);
        }

        public void Dispose()
        {
        }

        public async Task<List<AppUser>> GetAll()
        {
            return await _userStore.EntitySet.ToListAsync();
        }

        public async Task CreateAsync(AppUser user)
        {
            _userStore.Create(user);
            await SaveChanges();
        }

        public Task UpdateAsync(AppUser user)
        {
            return new Task(() => _identityDataDbContext.Users.Find(user.Id));
        }

        public Task DeleteAsync(AppUser user)
        {
            return new Task(() => _identityDataDbContext.Users.Remove(user));
        }

        public Task<AppUser> FindByIdAsync(string userId)
        {
            return new Task<AppUser>(() => _identityDataDbContext.Users.Find(userId));
        }

        public Task<AppUser> FindByNameAsync(string userName)
        {
            return Task.FromResult(
                _userStore.EntitySet.FirstOrDefault(u => u.UserName.ToUpper() == userName.ToUpper()));
        }

        public Task SetPasswordHashAsync(AppUser user, string passwordHash)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            user.PasswordHash = passwordHash;
            return Task.FromResult(0);
        }

        public Task<string> GetPasswordHashAsync(AppUser user)
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            return Task.FromResult(user.PasswordHash);
        }

        public Task<bool> HasPasswordAsync(AppUser user)
        {
            throw new NotImplementedException();
        }

        private async Task SaveChanges()
        {
            await _identityDataDbContext.SaveChangesAsync();
        }
    }
}